package storeSortingWeighRecord

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"github.com/shopspring/decimal"
	"insighttracking/apps/sorting/auth"
	"insighttracking/query/dao"
	"insighttracking/query/model"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/sorting/internal/svc"
	"insighttracking/apps/sorting/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type CreateStoreSortingWeighRecordApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewCreateStoreSortingWeighRecordApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *CreateStoreSortingWeighRecordApiLogic {
	hostname, _ := os.Hostname()
	return &CreateStoreSortingWeighRecordApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *CreateStoreSortingWeighRecordApiLogic) CreateStoreSortingWeighRecordApi(req *types.CreateStoreSortingWeighRecordReq) (resp string, err error) {
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return "", err
	}
	tx := dao.Use(l.svcCtx.MysqlDb).Begin()
	weight, _ := decimal.NewFromString(req.Weight)
	if err = service.StoreSortingWeighRecordService.CreateStoreSortingWeighRecordApi(l.ctx, tx, &model.StoreSortingWeighRecordEntity{
		OrdersID:       req.OrdersID,
		OrdersDetailID: req.OrdersDetailID,
		Weight:         weight,
		EnterpriseID:   accountInfo.EnterpriseId,
	}); err != nil {
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		logx.WithContext(l.ctx).Infof("创建失败:%v", err)
		return "", errors.New("创建失败")
	}
	if err = tx.Commit(); err != nil {
		return "", errors.New("创建失败")
	}
	return "操作成功", nil
}
